#!/usr/bin/env bash

source ~/.bash_profile

GIT_DIR=$HOME/code
CMD=$1
MODULE_NAME=$2
PROJECT_DIR=/root/deploy/code/cool-school
CURR_DIR=`pwd`
cd $PROJECT_DIR

case $MODULE_NAME in
	cool-school) MODULE_DIR=$PROJECT_DIR/cool-school;;
esac

if [ $CMD == "build" ]; then
  git reset --hard origin/master
	git pull
	echo "git pull success"
	mvn clean package -Dmaven.test.skip=true
	chmod -R 777 /root/deploy/code/cool-school
  echo "mvn build success"

	if [ $? != 0 ]; then
		echo "mvn build failed"
		exit
	fi
fi


PROFILE="pro"
case $MODULE_NAME in
	cool-school) JAVA_OPTS="-jar -Xloggc:$MODULE_NAME_jvm.log -server -Xms1500m -Xmx1500m" ;;
esac
JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=$PROFILE"

kill_module_process(){
	MODULE_PROCESS_ID=`ps axu | grep $1 |grep java | awk '{print $2}'`
	if [ "X$MODULE_PROCESS_ID" == "X" ]; then
		return 0
	fi
	echo "killing $MODULE_PROCESS_ID ..."
	echo "restart $MODULE_NAME ..."
	while /bin/true
	do
		kill $MODULE_PROCESS_ID
		sleep 1
		MODULE_PROCESS_ID=`ps axu | grep $1 |grep java | awk '{print $2}'`
		if [ "X$MODULE_PROCESS_ID" == "X" ]; then
			return 0
		fi
	done
}




LOG_FILE="$CURR_DIR/$MODULE_NAME.log"
if [ $CMD == "run" ]; then
	kill_module_process $MODULE_NAME
	BUILD_DIR=$MODULE_DIR/target
	cd $BUILD_DIR
	nohup  java $JAVA_OPTS `find ./ -name "*.jar"` 1>$LOG_FILE &2>1
	echo $JAVA_OPTS
	echo $LOG_FILE
	sleep 1
	tail -f $LOG_FILE
fi



